package org.xm.moretriggercommands.Event;

import org.bukkit.Bukkit;
import org.bukkit.plugin.Plugin;
import org.xm.moretriggercommands.Main;

public class TPSUtil {
    private final Plugin plugin;
    private long lastTickTime;
    private int currentTick;
    private double averageTPS;
    // 添加冷却时间相关变量
    private long lastExecuteTime = 0;  // 上次执行命令的时间
    private int cooldownSeconds;       // 冷却时间(秒)

    public TPSUtil(Plugin plugin) {
        this.plugin = plugin;
        this.lastTickTime = System.currentTimeMillis();
        this.currentTick = 0;
        this.averageTPS = 20.0;
        // 从配置中获取冷却时间，默认为60秒


        Bukkit.getScheduler().runTaskTimer(plugin, this::update, 0L, 1L);
    }

    public void update() {
        if (Main.getInstance().getConfig().getBoolean("TPScommand.Switch", false)) {
            this.cooldownSeconds = Main.getInstance().getConfig().getInt("TPScommand.Cooldown");
            int TPStime = Main.getInstance().getConfig().getInt("TPScommand.TPStime");
            int TPS = Main.getInstance().getConfig().getInt("TPScommand.TPSBelow");
            long now = System.currentTimeMillis();
            long tickDuration = now - lastTickTime;
            lastTickTime = now;

            currentTick++;
            if (currentTick % TPStime == 0) { // 多少秒执行一次检查
                double instantTPS = 1000.0 / tickDuration;
                String formattedTPS = String.format("%.1f", instantTPS);

                // 检查是否低于阈值且已过冷却时间
                if (instantTPS < TPS && isCooldownPassed(now)) {
                    // 记录当前执行时间
                    lastExecuteTime = now;

                    Bukkit.getScheduler().runTask(plugin, () -> {
                        for (String Command : Main.getInstance().getConfig().getStringList("TPScommand.TPScommand")) {
                            Command = Command.replace("%tps%", formattedTPS).replace("&", "§");
                            Bukkit.dispatchCommand(Bukkit.getConsoleSender(), Command);
                            this.cooldownSeconds = Main.getInstance().getConfig().getInt("TPScommand.Cooldown");
                        }
                    });
                }

                averageTPS = (averageTPS * 0.99) + (instantTPS * 0.01);
                currentTick = 0;
            }
        }
    }

    // 检查冷却时间是否已过
    private boolean isCooldownPassed(long currentTime) {
        // 计算距离上次执行已经过了多少毫秒
        long elapsedTime = currentTime - lastExecuteTime;
        // 转换冷却时间为毫秒并比较
        return elapsedTime >= cooldownSeconds * 1000L;
    }

    public double getAverageTPS() {
        return averageTPS;
    }
}
